import { createElement } from './Util';
import ErTableField from './ErTableField';
import ErBase from './ErBase';


class ErTable extends ErBase {
  constructor(options, er) {
    super();
    this.type = 'ErTable';
    this.er = er;
    this.id = options.id;
    this.fields = [];
    this.options = options;
    this.createEl();
    this.updateName();
    this.updatePos(options.top, options.left);
    options.fields.forEach(f => this.addField(f));
  }

  createEl() {
    this.el = createElement('div', {
      'data-id': this.id,
      class: 'er-table',
    });
    this.elHeader = createElement('div', {
      class: 'er-table-header'
    });

    this.elBody = createElement('div', {
      class: 'er-table-body',
    });
    this.elBottom = createElement('div', {
      class: 'er-table-bottom',
      style: 'height: 8px;background: grey;'
    });
    this.el.appendChild(this.elHeader);
    this.el.appendChild(this.elBody);
    this.el.appendChild(this.elBottom);

    this.el.querySelector('.er-table-body').addEventListener('scroll', (e) => {
      this.er.repaint();
    });
  }

  updateName() {
    if(this.options.number){
      const bef = createElement('div', {
        style: 'width: 60%;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;display: inline-block;'
      })
      bef.innerText = this.options.name
      const after = createElement('div', {
        style: 'float: right;font-size: 10px;margin-right:1px;'
      })
      after.innerText = '次数';
      const ext = createElement('input', {
        id: this.options.id,
        style: 'float: right;width: 20%;margin-right:1px;margin-bottom:1px;',
        value: this.options.number,
        type: 'number',
        min: 1,
        max: 30,
        step: 1
      })
      this.elHeader.appendChild(bef)
      this.elHeader.appendChild(ext)
      this.elHeader.appendChild(after)

    }else {
      this.elHeader.innerText = this.options.name;
    }
  }

  updateSize(width, height) {
    this.width = width;
    this.height = height;
    this.options.width = width;
    this.options.height = height;
    this.el.style.width = width + 'px';
    this.el.style.height = height + 'px';
  }

  updatePos(top, left) {
    this.top = top;
    this.left = left;
    this.el.style.top = top + 'px';
    this.el.style.left = left + 'px';
  }

  addField(field) {
    let erField = new ErTableField(field, this);
    this.fields.push(erField);
    this.elBody.appendChild(erField.el);
  }

  findField(id) {
    return this.fields.find(f => f.id == id);
  }

  remove() {
    this.er.removeTableLines(this.id);
    this.el.parentElement.removeChild(this.el);
  }

  toJSON() {
    var inputElement = document.getElementById(this.options.id);
    this.options.number = inputElement.value;
    console.log("new value:", this.options)
    return Object.assign({}, this.options, {
      fields: this.fields.map(f => f.toJSON()),
    });
  }

}

export default ErTable;
